﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;

namespace InventoryPro.DAL
{
    public class ProductDAO
    {
        InvEntities context ;
        public ProductDAO() 
        {
             
        context = new InvEntities(); 
        }

        public List<Product> GetAllProducts()
        {

           //InvEntities context = new InvEntities();
            
            var query = from p in context.Products
                        orderby p.CategoryID
                        select p;
 
            //var queryResult = (((ObjectQuery)query).Execute(MergeOption.AppendOnly));
            //             context.Dispose();

           return  query.ToList<Product>();
            
         }

        
        public Product  GetProductbyID(int ID)

        {
            Product product = null;
            var query = from p in context.Products
                        where p.ProductID == ID
                        select p;
            var Q = (((ObjectQuery)query).Execute(MergeOption.AppendOnly));
            foreach (Product p in Q)
            {
                product = p;                
            }

            if(product != null)
            context.Detach(product);
            return product;
        }


        public void CreateProduct(Product product)

        {
            context.AddToProducts(product);
            context.SaveChanges();

        }


        public  void  UpdateProduct(Product product)

        {
           
            context.Attach(product);
             context.SaveChanges();
        }


         public  void  DeleteProduct(int ID)

        {
           Product product = null;
            var query = from p in context.Products
                        where p.ProductID == ID
                        select p;
            var Q = (((ObjectQuery)query).Execute(MergeOption.AppendOnly));
            foreach (Product p in Q)
            {
                product = p;                
            }

             context.DeleteObject(product);
            
        }

         public List<Category> GetAllCategories()
         {
             var query = from c in context.Categories
                         orderby c.CategoryName
                         select c;

             return query.ToList<Category>();
         }



        }
}




